<template>
  <div class="app-container" v-loading="loading">
    <el-descriptions title="基本信息" :column="3">
      <el-descriptions-item label="售后编号">{{
        detail.returnNo
      }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{
        detail.createTime
      }}</el-descriptions-item>
      <el-descriptions-item label="售后状态">
        {{
          detail.status === 0
            ? '待审核'
            : detail.status === 1
            ? '待寄件'
            : detail.status === 2
            ? '待收件'
            : detail.status === 3
            ? '退款成功'
            : detail.status === 4
            ? '退款成功'
            : detail.status === 5
            ? '已取消'
            : detail.status === 6
            ? '退款失败'
            : detail.status === 7
            ? '退款关闭'
            : ''
        }}
      </el-descriptions-item>
      <el-descriptions-item label="用户昵称">{{
        detail.userNickName
      }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{
        detail.userPhone
      }}</el-descriptions-item>
      <el-descriptions-item label="订单编号">{{
        detail.orderNo
      }}</el-descriptions-item>
      <el-descriptions-item label="实付金额">{{
        detail.orderRealPayRmb
      }}</el-descriptions-item>
      <el-descriptions-item :span="2" label="运费">{{
        detail.freight
      }}</el-descriptions-item>
      <el-descriptions-item label="退款原因">{{
        detail.returnReason
      }}</el-descriptions-item>
      <el-descriptions-item :span="2" label="问题说明">{{
        detail.reasonDescription
      }}</el-descriptions-item>
      <el-descriptions-item label="售后类型">
        {{
          detail.returnType === 1
            ? '仅退款'
            : detail.returnType === 2
            ? '退货'
            : detail.returnType === 3
            ? '退货退款'
            : ''
        }}
      </el-descriptions-item>
      <el-descriptions-item label="申请退款金额">{{
        detail.applyRmb
      }}</el-descriptions-item>
      <el-descriptions-item label="实际退款金额">{{
        detail.realRmb
      }}</el-descriptions-item>
      <el-descriptions-item label="上传凭证">
        <ImagePreview
          v-for="item in detail.voucherImg"
          :src="item"
          :key="item"
        />
        <!-- <ImagePreview :src="detail.voucherImg || ''" /> -->
      </el-descriptions-item>
      <el-descriptions-item v-if="detail.status == 2" :span="2" label="查看物流"
        ><span
          @click="click().handleExpress()"
          style="color: #1890ff; cursor: pointer"
          >点击</span
        ></el-descriptions-item
      >
    </el-descriptions>

    <div style="margin: 20px 0; font-weight: bold">商品信息</div>
    <el-table
      :data="tableData"
      border
      style="width: 50vw"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column prop="id" label="商品ID"> </el-table-column>
      <el-table-column prop="goodsName" label="商品名称"> </el-table-column>
      <el-table-column prop="goodsSpecificationsName" label="规格">
      </el-table-column>
      <el-table-column prop="platformPrice" label="售价(元)"> </el-table-column>
      <el-table-column prop="goodsNum" label="购买数量"> </el-table-column>
    </el-table>

    <div style="margin: 20px 0; font-weight: bold">审核信息</div>

    <el-button
      v-if="detail.status == 0"
      type="primary"
      @click="click().handleReview()"
      >审核</el-button
    >
    <!-- 审核信息 -->
    <el-descriptions :column="3" v-if="detail.status !== 0">
      <el-descriptions-item label="审核意见">{{
        auditInfo.auditStatus == 1
          ? '通过'
          : auditInfo.auditStatus == 2
          ? '驳回'
          : auditInfo.auditStatus == 0
          ? '待审核'
          : ''
      }}</el-descriptions-item>
      <el-descriptions-item :span="2" label="审核时间">{{
        auditInfo.auditTime
      }}</el-descriptions-item>
      <el-descriptions-item label="审核人">{{
        auditInfo.auditSysUserName
      }}</el-descriptions-item>
      <el-descriptions-item
        :span="2"
        label="备注"
        v-if="auditInfo.auditReason"
        >{{ auditInfo.auditReason }}</el-descriptions-item
      >
      <el-descriptions-item
        :span="2"
        label="驳回理由"
        v-if="auditInfo.auditStatus == 2"
        >{{ auditInfo.auditReason }}</el-descriptions-item
      >
    </el-descriptions>

    <!-- v-if="detail.status === 2" -->
    <el-button
      type="primary"
      v-if="getStatusActions(detail.status).PickUp"
      @click="click().handleComfirm()"
      >确认收件</el-button
    >
    <!-- 审核弹窗 -->
    <el-dialog
      title="审核"
      :visible.sync="audit.auditDialog"
      width="30%"
      class="dialog-container"
    >
      <el-form
        ref="dialogData"
        :rules="audit.dialogRules"
        label-suffix=":"
        :model="audit.dialogData"
      >
        <el-form-item prop="auditStatus" label="审核意见" label-width="90px">
          <el-select
            v-model="audit.dialogData.auditStatus"
            placeholder="请选择"
            size="mini"
          >
            <el-option label="通过" value="1"></el-option>
            <el-option label="驳回" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="audit.dialogData.auditStatus == '1'"
          label="退款金额"
          prop="refundRmb"
          label-width="90px"
        >
          <el-input
            placeholder="请输入金额"
            v-model="audit.dialogData.refundRmb"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="audit.dialogData.auditStatus == '1'"
          prop="remarkVal"
          label="备注"
          label-width="90px"
        >
          <el-input placeholder="请输入，最多100字" v-model="audit.remarkVal">
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="audit.dialogData.auditStatus == '2'"
          prop="auditReason"
          label="驳回理由"
          label-width="90px"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入驳回理由,最多输入100字"
            v-model="audit.dialogData.auditReason"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="click().handleClose('dialogData')">取 消</el-button>
        <el-button type="primary" @click="click().handleStatus('dialogData')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 查看物流 -->
    <el-dialog
      title="查看物流"
      :visible.sync="express.dialog"
      width="45%"
      class="expressDialog"
    >
      <div class="infoBox">
        <p class="tit">商品信息</p>
        <div class="expressInfo">
          <p><strong>商品名称：</strong>{{ goodsBaseInfo.name }}</p>
          <p><strong>商品规格：</strong>{{ goodsBaseInfo.spec }}</p>
          <p>
            <strong>物流状态：</strong
            >{{
              express.expressStatus === '0'
                ? '在途'
                : express.expressStatus === '1'
                ? '揽收'
                : express.expressStatus === '2'
                ? '疑难'
                : express.expressStatus === '3'
                ? '签收'
                : express.expressStatus === '4'
                ? '退签'
                : express.expressStatus === '5'
                ? '派件'
                : express.expressStatus === '6'
                ? '退回'
                : express.expressStatus === '7'
                ? '转投'
                : express.expressStatus === '10'
                ? '待清关'
                : express.expressStatus === '11'
                ? '清关中'
                : express.expressStatus === '12'
                ? '已清关'
                : express.expressStatus === '13'
                ? '清关异常'
                : express.expressStatus === '14'
                ? '拒签'
                : ''
            }}
          </p>
          <p>
            <strong>{{ goodsBaseInfo.logisticsName }}</strong>
            {{ goodsBaseInfo.logisticsNo }}
          </p>

          <div style="height: 300px">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in express.expressSteps"
                :key="index"
                :color="index == 0 ? '#409eff' : ''"
                :size="item.size"
                :timestamp="item.ftime"
                :type="item.type"
              >
                {{ item.context }}
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
      <p class="backBtn">
        <el-button size="mini" @click="click().handleExpressBack()"
          >返回</el-button
        >
      </p>
    </el-dialog>
  </div>
</template>
<script>
import {
  getRefundDetail,
  comfirmOrder,
  examineOrder,
} from '@/api/merchant-order-manage/aftermarket-orders.js';
import { getCompanyList } from '@/api/merchant-order-manage/aftermarket-orders.js';
import { getExpressInfo } from '@/api/merchant-order-manage/aftermarket-orders.js';
import {getStatusActions} from '@/utils/status.js'
export default {
  data() {
    var validateRmb = (rule, value, callback) => {
      if (+value > +this.detail.orderRealPayRmb) {
        callback(new Error('退款金额不能大于实付款金额'));
      }
      if (!value) {
        callback(new Error());
      } else {
        callback();
      }
    };
    return {
      loading: false,
      detail: {},
      componentId: null,
      id: '',
      // 审核信息
      auditInfo: {},
      tableData: [],
      // 物流公司
      companyOptions: [],
      // 查看物流：商品基本信息
      goodsBaseInfo: {
        name: '',
        spec: '',
        logisticsNo: '',
      },
      // 查看物流对话框数据
      express: {
        dialog: false,
        expressSteps: [],
        expressStatus: '',
      },
      // 审核弹窗数组对象
      audit: {
        // 退款成功备注
        remarkVal: '',
        // 审核弹出框
        auditDialog: false,
        // 审核弹出框弹出框内容
        dialogData: {
          auditReason: '',

          refundRmb: '',
          auditStatus: '',
          id: '',
        },
        // 对话框校验对象
        dialogRules: {
          auditStatus: [
            { required: true, message: '请选择审核意见', trigger: 'change' },
          ],
          refundRmb: [
            { required: true, message: '请输入退款金额', trigger: 'change' },
            {
              validator: validateRmb,
              required: true,
              message: '退款金额不能大于实付款金额',
              trigger: 'change',
            },
          ],
          auditReason: [
            {
              required: true,
              max: 100,
              message: '请输入驳回理由',
              trigger: 'blur',
            },
          ],
        },
      },
      // 接口存储对象：five step
      interfaceObj: {
        examineApiName: examineOrder,
      },
    };
  },

  created() {
    this.network().getDetail();
    this.network().getCompany();
  },
  methods: {
    getStatusActions,
    click() {
      return {
        // 审核
        handleReview: async (row) => {
          this.audit.auditDialog = true;
          this.audit.dialogData.id = this.id;
        },
        // 审核 - 取消 - 关闭对话框
        handleClose: async (formName) => {
          this.audit.auditDialog = false;
          this.$refs[formName].resetFields();
          this.audit.remarkVal = '';
        },
        // 审核 - 确定 - 关闭对话框
        handleStatus: async (formName) => {
          const throttleStatus = this.throttle(); // 节流
          if (!throttleStatus) return;
          this.$refs[formName].validate((valid) => {
            if (valid) {
              const newObj = JSON.parse(JSON.stringify(this.audit.dialogData));
              newObj.auditStatus = Number(this.audit.dialogData.auditStatus);
              if (newObj.auditStatus == 1) {
                newObj.auditReason = this.audit.remarkVal;
              }
              if (newObj.auditReason == '' && newObj.auditStatus == 2) {
                this.$message({
                  message: '请填写驳回理由',
                  type: 'warning',
                });
                return;
              }
              this.network().changeStatus(newObj);
            } else {
              return false;
            }
          });
        },
        // 确认收货
        handleComfirm: async () => {
          this.deleteMessageBox({
            message: '是否确认收件？',
            hideTit: true,
          }).then(() => {
            this.network().handleComfirm(this.id);
          });
        },
        // 查看物流
        handleExpress: async () => {
          this.express.dialog = true;
          this.goodsBaseInfo.name = this.detail.goodsName;
          this.goodsBaseInfo.spec = this.tableData[0].goodsSpecificationsName;
          this.goodsBaseInfo.logisticsNo = this.detail.logisticsNo;
          this.goodsBaseInfo.logisticsName = this.detail.logisticsName;
          // 快递公司名称中文转拼音
          const it = this.companyOptions.find((item) => {
            return item.name == this.detail.logisticsName;
          });
          this.network().getExpressInfo({
            name: this.detail.logisticsNo,
            code: it.code,
            phone: this.detail.userPhone,
          });
        },
        handleExpressBack: async () => {
          this.express.dialog = false;
        },
      };
    },
    network() {
      return {
        getDetail: async () => {
          const { uuid } = this.$route.params;
          this.id = uuid;
          this.loading = true;
          try {
            const { data } = await getRefundDetail({ id: uuid });
            this.loading = false;
            this.detail = data;
            Object.assign(this.detail, data, {
              voucherImg:
                typeof data.voucherImg === 'string'
                  ? data.voucherImg.split(',')
                  : [],
            });
            this.$set(this.tableData, 0, data.martGoodsBaseDetailVo);
            this.tableData[0].goodsNum = data.goodsNum;
            this.tableData[0].goodsSpecificationsName =
              data.martGoodsBaseDetailVo.goodsSpecificationsGroupRos
                .map((item) => {
                  return item.goodsSpecificationsRos
                    .map((it) => it.specificationsName)
                    .join();
                })
                .join();
            this.tableData[0].platformPrice =
              data.martGoodsBaseDetailVo.goodsSpecificationsGroupRos
                .map((item) => {
                  return item.goodsSpecificationsRos
                    .map((it) => it.platformPrice)
                    .join();
                })
                .join();

            this.auditInfo = data.martAuditRecordVo;
          } catch (error) {
            console.log('error');
            this.loading = false;
          }
        },
        // 获取快递公司
        getCompany: async () => {
          const data = await getCompanyList();
          this.companyOptions = data.rows;
        },
        // 审核
        changeStatus: async (obj) => {
          const { examineApiName } = this.interfaceObj;
          const data = await examineApiName(obj);
          if (data.code == 0) {
            this.$message.success('提交成功');
            this.network().getDetail();
            this.audit.auditDialog = false;
            this.$refs['dialogData'].resetFields();
            this.audit.remarkVal = '';
            return false;
          }
          return this.$message.error('提交失败');
        },
        handleComfirm: async (id) => {
          const { code } = await comfirmOrder( id );
          if (code === 0) {
            this.$modal.msgSuccess('提交成功');
          }
          this.network().getDetail();
        },
        // 查看物流
        getExpressInfo: async (obj) => {
          const { data } = await getExpressInfo(obj);

          this.express.expressSteps = data.data;
          this.express.expressStatus = data.state;
        },
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 40px;
}
::v-deep {
  .el-descriptions-item__container {
    display: flex;
  }
}
.dialog-container {
  margin-top: 80px;
  ::v-deep.el-select {
    width: 100%;
  }
}
.expressDialog {
  ::v-deep .el-dialog {
    height: 90vh;
  }
  ::v-deep.el-dialog__body {
    padding: 10px 20px;
  }
  .infoBox {
    border: 1px solid #ccc;
    height: 72vh;
    overflow: auto;
    padding: 15px 10px;
    .tit {
      font-size: 14px;
      font-weight: bold;
      margin: 0;
      padding-bottom: 15px;
      border-bottom: 1px solid #ccc;
    }
    .expressInfo {
      padding: 10px 15px;
      font-size: 12px;
    }
  }
  .backBtn {
    display: flex;
    justify-content: right;
  }
  ::v-deep .el-timeline {
    padding-left: 20px;
  }
}
</style>
